package thread;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;

/**
 * @author Duanyu
 * @date 2021-11-18 10:01
 */
public class ReadWriteTest {

    public static void main(String[] args) {
        Cache cache = new Cache();
        //5个线程写数据
        Stream.of("A", "B", "C", "D", "E").forEach(v -> new Thread(() -> cache.set(v, v), v).start());

        //5个线程读数据
        Stream.of("A", "B", "C", "D", "E").forEach(v -> new Thread(() -> cache.get(v), v).start());
    }




}

class Cache {

    private volatile Map<String, Object> map = new HashMap<>();

    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    //写数据
    public void set(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            //暂停一会
            System.out.println(Thread.currentThread().getName() + "写：" + key);
            TimeUnit.SECONDS.sleep(2);

            //写
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写结束：" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    //读数据
    public Object get(String key) {
        Object result = null;
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在读取：" + key);
            //暂停一会
            TimeUnit.SECONDS.sleep(2);

            result = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读完了：" + key+"--"+result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return result;
    }

}
